package kiven.jee.model.support;

import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

import kiven.jee.model.TreeEntity;

public class TreeEntityUtil {
	/**
	 * 不允许将外键关系设置成环. 就是说，当前的current的子节点中，如果包含parent，就不能把parent设置为current的上级节.
	 * @param current
	 * @param parentNode
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <E extends TreeEntity> boolean isDeadLock(
			TreeEntity<E> current, TreeEntity<E> parentNode) {
		if (current == null || parentNode == null || current.equals(parentNode)) {
			return true;
		} else {
			for (TreeEntity<E> child : current.getChildren()) {
				boolean isDeadLock = isDeadLock(child,parentNode);
				if (isDeadLock) {
					return true;
				}
			}
		}
		
		return false;
	}
	
	/**
	 * 得到TreeEntity自己和所有的孩子列表
	 * @param me
	 * @return
	 */
	@SuppressWarnings({"rawtypes","unchecked"})
	public static <E extends TreeEntity> Set<E> getMeAndListChildrent(E me) {
		Set<E> hashSet = new HashSet<E>();
		hashSet.add(me);
		Set<E> children = me.getChildren();
		for (E e : children) {
			hashSet.addAll(getMeAndListChildrent(e));
		}
		
		return hashSet;
	}
	
	/**
	 * 得到TreeEntity自己所有的孩子（包括树干和叶子节点).
	 * @param me
	 * @return
	 */
	@SuppressWarnings({"rawtypes","unchecked"})
	public static <E extends TreeEntity> Set<E> getAllChildren(E me) {
		Set<E> list = new HashSet<E>();
		Stack<E> stack = new Stack<E>();
		stack.push(me);
		
		while(!stack.isEmpty()) {
			E e = stack.pop();
			list.add(e);
			
			Set<E> children = e.getChildren();
			
			for (E ac : children) {
				stack.push(ac);
			}
		}
		
		list.remove(me);
		return list;
	}
	
	/**
	 * 得到TreeEntity自己所有的叶子节点
	 * 
	 * @param <E>
	 * @param me
	 *            TreeEntity
	 * @return List
	 */
	@SuppressWarnings("rawtypes")
	public static <E extends TreeEntity> Set<E> getAllLeaves(E me) {
		Set<E> allChildren = getAllChildren(me);
		Set<E> list = new HashSet<E>();
		list.addAll(allChildren);
		
		for (E e : allChildren) {
			if (!e.isLeaf()) {
				list.remove(e);
			}
		}
		
		return list;
	}
	
	/**
	 * 本节点是否为某节点的父亲节点
	 * 
	 * @param parent
	 * @param son
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <E extends TreeEntity> boolean isParentOf(
			TreeEntity<E> parent, TreeEntity<E> son) {
		if (son == null || son.equals(parent)) {
			return false;
		} else if (parent.isLeaf()) {
			return false;
		} else if (son.isRoot()) {
			return false;
		} else {
			TreeEntity<E> bt = son.getParent();
			if (parent.equals(bt)) {
				/* 如果对方的父节点是自己,则返回TRUE */
				return true;
			} else {
				/* 判断对方的父节点是否是自己的孩子,进行递归 */
				return isParentOf(parent,bt);
			}
			
		}
	}
}
